﻿using System;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using Infrastucture.Events;
using System.Windows;

namespace Infrastucture.View
{
    public class ShellViewModel : BindableBase
    {
        private BackgroundSubscriber _subscriber;
        private IEventAggregator _eventAggragator;

        public ShellViewModel(IEventAggregator eventAggragator)
        {
            _eventAggragator = eventAggragator;


            AddBackgroundSubscriberCommand = new DelegateCommand(addBackgroundSubscriber);
            GCBackgroundSubscriberCommand = new DelegateCommand(gcBackgroundSubscriber);
        }


        public DelegateCommand AddBackgroundSubscriberCommand { get; private set; }
        public DelegateCommand GCBackgroundSubscriberCommand { get; private set; }


        private void addBackgroundSubscriber()
        {
            if (_subscriber != null) return;

            _subscriber = new BackgroundSubscriber(Application.Current.Dispatcher);

            var e = _eventAggragator.GetEvent<NavigationEvent>();
            e.Subscribe(_subscriber.HandleNavigationChange);
        }

        private void gcBackgroundSubscriber()
        {
            _subscriber = null;
            GC.Collect();
        }
    }
}
